import {
    Inject, Controller, Post, Get,
    Body, Query
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/user.service';
import { RoleService } from '../service/role.service';
import { User } from '../entity/user.entity';

@Controller('/user')
export class UserController {
    @Inject()
    ctx: Context;

    @Inject()
    userService: UserService;
    
    @Inject()
    roleService: RoleService;

    @Post('/create')
    async create(@Body() user: Partial<User>) {
        try {
            const result = await this.userService.create(user);
            return {
                code: 200,
                message: '创建成功',
                data: result
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '创建失败'
            };
        }
    }

    @Post('/update')
    async update(@Body() user: Partial<User>) {
        try {
            const success = await this.userService.update(user.id, user);
            return {
                code: 200,
                message: success ? '更新成功' : '更新失败'
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '更新失败'
            };
        }
    }

    @Get('/del')
    async delete(@Query('id') id: number,) {
        try {
            const success = await this.userService.delete(id);
            return {
                code: 200,
                message: success ? '删除成功' : '删除失败'
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '删除失败'
            };
        }
    }

    @Get('/detail')
    async getInfo(@Query('id') id: number) {
        try {
            const user = await this.userService.getInfo(id);
            return {
                code: 200,
                message: '获取成功',
                data: user
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '获取失败'
            };
        }
    }

    @Get('/list')
    async getList(
        @Query('page') page: number,
        @Query('pageSize') pageSize: number,
        @Query('username') username?: string,
        // @Query('status') status?: number,
        // @Query('deptId') deptId?: number
    ) {
        try {
            const [list, total] = await this.userService.getList({
                page,
                pageSize,
                username,
                // status,
                // deptId
            });

            return {
                code: 200,
                message: '获取成功',
                data: list,
                total
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '获取失败'
            };
        }
    }

    @Get('/userInfo')
    async getCurrentUser() {
        try {
            // 从JWT中获取用户ID
            const userId = this.ctx.state.user.uid;
            
            // 调用userService获取完整的用户信息
            const user = await this.userService.getInfo(userId);
            
            if (!user) {
                return {
                    code: 404,
                    message: '用户不存在'
                };
            }
            
            // 获取用户角色下的所有权限
            const permissions = [];
            if (user.roleIds && user.roleIds.length > 0) {
                // 遍历用户的所有角色，获取每个角色的权限
                for (const roleId of user.roleIds) {
                    try {
                        const rolePermissions = await this.roleService.getRolePermissions(roleId);
                        if (rolePermissions && rolePermissions.length > 0) {
                            // 合并权限，避免重复
                            for (const perm of rolePermissions) {
                                if (!permissions.find(p => p.id === perm.id)) {
                                    permissions.push(perm);
                                }
                            }
                        }
                    } catch (err) {
                        // 如果某个角色获取权限失败，继续处理其他角色
                        console.error(`获取角色ID ${roleId} 的权限失败:`, err);
                    }
                }
            }
            
            return {
                code: 200,
                message: '获取成功',
                data: {
                    ...user,
                    permissions
                }
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '获取用户信息失败'
            };
        }
    }
}